﻿namespace Spotted.Storage.Blobs
{
    using System;
    using System.Device.Location;
    using System.Windows;
    using System.Windows.Navigation;
    using Microsoft.Phone.Tasks;
    using Microsoft.WindowsAzure.Samples.Phone.Storage;
    using System.IO;
    using System.Windows.Media.Imaging;
    using System.ComponentModel;
    using Spotted.DBReference;
    using System.Text.RegularExpressions;

    /**
     * API for Blob Storage on Azure - upload,download and delete 
     * 
     * */
    
    
    public partial class BlobAPI
    {
        

        private string containerName;
        private string blobName;
        private bool isUploading;
        private bool isPublic;
        private Service1Client _serviceClient;
        private App app = Application.Current as App;
       
        public double Perimeter;
        public double Area;
        public String melanoma;
        public String blob_Url;


        private Stream photoStream;

        public BlobAPI(EventHandler<AddImageCompletedEventArgs>AddImageCompleted)
        {

            containerName = "public";
            isPublic = true;

            isUploading = false;
            _serviceClient = new Service1Client();
            _serviceClient.AddImageCompleted +=  AddImageCompleted;

        }

        public void LoadPhotoInfoToBlob(PhotoResult photoResult)
        {
            if (photoResult.TaskResult == TaskResult.OK)
            {
                this.blobName = string.Format("Capture-{0}", DateTime.Now.ToString("yyyyMMddTHHmmss"));
                    
                this.photoStream = photoResult.ChosenPhoto;
            }
        }

        public BitmapImage showPhoto(String blobUrl)
        {   
            Uri uri = new Uri("blobUrl");
            return new BitmapImage(uri);

        }

        public String uploadPhoto()
        {
            this.isUploading = true;
            var blobClient = CloudStorageContext.Current.Resolver.CreateCloudBlobClient();
            var container = blobClient.GetContainerReference(this.containerName);

            String blobUrl = null;
            container.CreateIfNotExist(
                this.isPublic ? BlobContainerPublicAccessType.Container : BlobContainerPublicAccessType.Off,
                response =>
                {
                    if (response.Success)
                    {
                        var blob = container.GetBlobReference(this.blobName);
                        blob.Properties.ContentType = "image/jpeg";


                        blob.UploadFromStream(
                            photoStream,
                            response2 =>
                            {
                                if (response2.Success)
                                {

                                    MessageBox.Show(string.Format("Image file {0} successfully uploaded to Azure Storage!", this.blobName));

                                    blobUrl = "http://portalvhdsw254ps4cgcsr1.blob.core.windows.net/public/" + this.blobName;
                                     Action callback = () =>  parseResults(Classifier.feed,blobUrl); 
                                    Classifier.classifyTest(blobUrl,callback);
                                   

                                }
                                else
                                {

                                    MessageBox.Show(string.Concat("Error: ", response.ErrorMessage));
                                }
                            });
                    }
                });
            return blobUrl;
        }

        private void parseResults(String response,String blobUrl)
        {
            //Double Perimeter = -1;
            //Double Area = -1;
            //Double Diameter = -1;
            //Double Asymmetry = -1;
            //Double BoundaryIrregularity = -1;
            //Double AverageR = -1;
            //Double AverageG = -1;
            //Double AverageB = -1;
            //Double DominantR = -1;
            //Double DominantG = -1;
            //Double DominantB = -1;
            //Double AverageH = -1;
            //Double AverageS = -1;
            //Double AverageI = -1;
            //Double DominantH = -1;
            //Double DominantS = -1;
            //Double DominantI = -1;
            //Double Entropy = -1;
            //Double Energy = -1;
            //Double Inertia = -1;
            //Double Homogeneity = -1;
            //Double NumberSubregions = -1;
            //Double NumberSubregionTypes = -1;
          
            String line = Regex.Split(response, "<h3>")[1];
            line = Regex.Split(line, "</h3>")[0];
            String[] values = line.Split(',');
            if (!values[0].Contains("?"))
            Perimeter=Double.Parse(values[0]);
            if (!values[1].Contains("?"))
            Area=Double.Parse(values[1]);
            melanoma = values[values.Length-1];
            blob_Url = blobUrl;
            
            
            _serviceClient.AddImageAsync(blobUrl, DateTime.Now, Perimeter, Area, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, Boolean.Parse(melanoma.Replace("\n","")));
          
        
        }

        

        public void DeleteBlob(String blobName)
        {
            var blobClient = CloudStorageContext.Current.Resolver.CreateCloudBlobClient();
            
            try
            {
                var currentBlob = blobClient.GetContainerReference(this.containerName).GetBlobReference(blobName);
                currentBlob.Delete(
                    response =>
                    {
                        if (response.Success)
                        {
                           MessageBox.Show("Blob successfully deleted");
                            
                        }
                        else
                        {
                            MessageBox.Show(string.Concat("Error: ", response.ErrorMessage));
                        }

                        
                    });
            }
            catch (Exception exception)
            {

                MessageBox.Show(string.Concat("Error: ", exception.Message));
            }
        }


    }







}